<template>
  <div class="todoapp">
    <TodoHeader :arr="showArr" @addTaskEvent="addTaskFn"></TodoHeader>
    <TodoMain :arr="showArr" @delEvent="delFn"></TodoMain>
    <TodoFooter :arr="showArr" @changeEnvet="changeFn" 
    @clearEvent="clearFn"></TodoFooter>
  </div>
</template>

<script>
// 1.0 样式引入
import "./styles/base.css"
import "./styles/index.css"
import TodoHeader from "./components/TodoHeader.vue"
import TodoMain from "./components/TodoMain.vue"
import TodoFooter from "./components/TodoFooter.vue"
export default {
  components: {
    // TodoHeader:TodoHeader
    TodoHeader,
    TodoMain,
    TodoFooter
  },
  data(){
    return {
      // list: [
      //   { id: 100, name: "吃饭", isDone: true },
      //   { id: 101, name: "睡觉", isDone: false },
      //   { id: 102, name: "打豆豆", isDone: true },
      // ],
      list: JSON.parse(localStorage.getItem("74-todolist"))||[],
      curType: "all"
    }
  },
  methods: {
    // 新增任务
    addTaskFn(name){
      if(!name){
        return alert("任务名不能为空！")
      }
      let id = this.list.length>0?
      this.list[this.list.length-1].id+1: 100
      this.list.push({
        id: id,
        name: name,
        isDone: false
      })
    },
    // 删除
    delFn(id){
      // 根据ID获取对应数组中的索引值
      // findIndex：这个方法用来查找并返回下标值，
      // 当符合条件判断的时候，这个方法就会立刻返回下标值。
      let index = this.list.findIndex(item=>item.id === id)
      this.list.splice(index, 1)
    },
    changeFn(type){
      this.curType = type
    },
    // 清空已完成，也就是留下未完成的数据
    clearFn(){
      this.list = this.list.filter(item=>{
        return item.isDone === false
      })
    }
  },
  computed: {
    showArr(){
      // 已完成
      if(this.curType === "yes"){
        let newArr= this.list.filter(item=>{
          return item.isDone === true
        })
        return newArr
      }else if(this.curType === "no"){
        // 未完成
        return this.list.filter(item=>{
          return item.isDone === false
        })
      }else{
        // 全部
        return this.list
      }
    }
  },
  watch: {
    list: {
      deep: true,
      handler(arr){
        // 数据发生变化进行实时缓存
        localStorage.setItem("74-todolist", JSON.stringify(arr))
      }
    }
  }
}
</script>

<style>

</style>